/**
 * 
 */
package com.kgcx.schedule.rabbitmq.consumer;

import java.util.List;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import com.kgcx.common.rabbitmq.consts.QueueConst;
import com.kgcx.common.utils.AuroraPush;
import com.kgcx.core.utils.HelpUtil;
import com.kgcx.dbutils.core.model.ParameterMap;
import com.kgcx.schedule.domain.ScheduleRecordDomain;
import com.kgcx.schedule.service.ScheduleRecordService;

/**
 * @author 袁进勇
 *
 */
@Component

public class NotifyPassengerConsumer {
    private static final Logger LOG = LoggerFactory.getLogger(NotifyPassengerConsumer.class);

    @Resource
    private ScheduleRecordService scheduleRecordService;

    @RabbitListener(queues = QueueConst.SCHEDULE_NOTIFY_PASSENGER_CITY, errorHandler = "custRabbitListenerErrorHandler")
    public void notifying(Long cityId) {
        LOG.info(String.format("收到给城市[%d]的乘客推送司机信息的MQ消息。", cityId));

        ParameterMap params = new ParameterMap("city_id", cityId);
        params.put("schedule_status", ScheduleRecordDomain.STATUS_NOTIFYING);
        params.put("notify_passenger_time_end", HelpUtil.getNowTime());
        List<ScheduleRecordDomain> records = scheduleRecordService.selectEntityListPage(params);
        if (HelpUtil.isEmpty(records)) {
            LOG.info("待推送司机信息的订单数为0。");
            return;
        }

        for (ScheduleRecordDomain record : records) {
            Long userId = record.getPassenger_id() == null ? record.getPlacing_user_id() : record.getPassenger_id();
            // 发送通知
            AuroraPush.pushTargetForUser(String.valueOf(userId),
                    String.format("您的用车需求已派单成功，已安排%s 电话%s 车牌%s。请年按时到达指定上车地点。", record.getDriver_name(),
                            record.getAuto_no(), record.getDriver_phone()));

            LOG.info(String.format("订单[%s]，给乘客[%d]推送司机信息成功。", record.getOrder_no(), userId));

            record.setSchedule_status(ScheduleRecordDomain.STATUS_NOTIFIED);
            scheduleRecordService.updateEntity(record);
        }
    }
}
